package com.cj.stock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cj.stock.dao.CategoryMapper;
import com.cj.stock.entity.Category;
import com.cj.stock.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author cheng jun
 * @Description:
 * @Date 2021/9/5 23:09
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Override
    public List<Category> findCategory() {

        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        int a = 2;
        int b = 3;
        queryWrapper.last("limit" + a + "," + b);
        // 查询所有类别
        List<Category> categories = this.list(null);

        // 组装树形结构
        List<Category> level1Menus = categories.stream().filter(category ->
            Objects.equals(category.getParentCid(), "0") && Objects.equals(category.getShowStatus(), 1)
        ).map(menu -> {
            menu.setChildren(getChildrens(menu, categories));
            return menu;
            // 排序
        }).sorted(Comparator.comparingInt(firstMenu -> (firstMenu.getSort() == null ? 0 : firstMenu.getSort()))
        ).collect(Collectors.toList());

        return level1Menus;
    }

    /**
     * 递归查找所有菜单的子菜单
     * @param root
     * @param categories
     * @return
     */
    private List<Category> getChildrens(Category root, List<Category> categories) {
        List<Category> categoryList = categories.stream().filter(category ->
                // 子菜单匹配
                Objects.equals(category.getParentCid(), String.valueOf(root.getCatId())) && Objects.equals
                        (category.getShowStatus(), 1)
        ).map(category -> {
            // children赋值
            category.setChildren(getChildrens(category, categories));
            return category;
            // 排序
        }).sorted(Comparator.comparingInt(firstMenu -> (firstMenu.getSort() == null ? 0 : firstMenu.getSort()))
        ).collect(Collectors.toList());

        return categoryList;
    }
}
